<?php

namespace  Aitels\Foundation\Route;

use Illuminate\Routing\Router;
use Illuminate\Routing\RouteRegistrar;
use Illuminate\Support\Facades\Route;
use  Aitels\Foundation\Code\ClassAnalyser;

class RouteBuilder
{
    public function buildRoute($classPath, $methodName, $definition)
    {
        $registrar = new RouteRegistrar(app(Router::class));

        if (isset($definition['domain']))
            $registrar->domain($definition['domain']);
        if (isset($definition['prefix']))
            $registrar->prefix($definition['prefix']);
        if (isset($definition['where']))
            $registrar->where($definition['where']);
        if (isset($definition['name']))
            $registrar->name($definition['name']);
        if (isset($definition['middleware']))
            $registrar->middleware($definition['middleware']);

        $registrar->group(function () use ($classPath, $methodName, $definition) {
            Route::match(
                $this->parseHttpMethods($definition),
                $this->parsePath($definition),
                $this->parseHandler($classPath, $methodName)
            );
        });
    }

    public function parsePath($definition)
    {
        return $definition['path'];
    }

    public function parseHandler($controllerPath, $methodName)
    {
        return sprintf("%s@%s", ClassAnalyser::getClassByPath($controllerPath), $methodName);
    }

    public function parseHttpMethods($definition)
    {
        if (isset($definition['method']))
            $httpMethods = explode(',', $definition['method']);
        return $httpMethods ?? ['get', 'head'];
    }

}